package com.kingschan.jeasytag.web.servlet;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.kingschan.jeasytag.container.EasyTagContainer;
import com.kingschan.jeasytag.container.impl.EasyTagContainerImpl;
import com.kingschan.jeasytag.sql.JdbcTemplete;
import com.kingschan.jeasytag.sql.connection.ConnectionFactory;
import com.kingschan.jeasytag.tag.power.SQLTag;
import com.kingschan.util.bean.BeanUtil;
import com.kingschan.util.web.ServletUtil;
/**
 * support combobox load ajax data
 * @author Administrator
 *
 */
@WebServlet(name="ComboboxServlet",urlPatterns="/jeasytag/combobox")
public class ComboboxServlet extends HttpServlet{
	private static Logger log = Logger.getLogger(ComboboxServlet.class);
	private static final long serialVersionUID = 1L;
	private EasyTagContainer container=EasyTagContainerImpl.getInstance();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		try {
			query( req,  resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * query model
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void query(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		String product="[]";
		Map<String, String> map = ServletUtil.getParameterMap(req);		
		if (map.containsKey("target")) {
			String path=container.getSerializationPath().concat(map.get("target")).concat(".data");
			SQLTag sqltag = (SQLTag) BeanUtil.DesSerializationObject(path);
			log.debug(sqltag.getSql());
			List<Map<String, Object>> data = JdbcTemplete.getListBySql(
				ConnectionFactory.getConn(sqltag.getJdbcConnection(), 
						container.getDefaultConnection()),sqltag.getSql(), true);
			JSONArray jsons = new JSONArray();	
			JSONObject json =null;
			for (int i = 0; i < data.size(); i++) {
				json = new JSONObject(data.get(i));
				jsons.put(json);
			}
			product=jsons.toString();
		}		
		resp.setContentType("text/html;charSet=gbk");
		PrintStream ps = new PrintStream(resp.getOutputStream());
		ps.print(product);
	}
	
}
